const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, '../uploads/avatars');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, 'avatar-' + uniqueSuffix + ext);
  }
});

const upload = multer({ storage: storage });

// 获取用户资料
router.get('/profile', async (req, res) => {
  try {
    console.log('获取用户资料请求:', req.query);
    
    // 从请求中获取用户ID
    const userId = req.query.userId || req.headers['userid'];
    
    if (!userId) {
      return res.status(400).json({ success: false, message: '缺少用户ID' });
    }
    
    // 查询用户信息 - 只查询基本字段
    const query = `
      SELECT * FROM users
      WHERE userId = ?
    `;
    
    const [results] = await pool.query(query, [userId]);
    
    if (results.length === 0) {
      return res.status(404).json({ success: false, message: '用户不存在' });
    }
    
    // 添加默认字段，以便前端代码不需要修改
    const userData = {
      ...results[0],
      bio: '', // 添加默认空bio字段
      gender: '' // 添加默认空gender字段
    };
    
    // 返回用户信息
    res.json({ success: true, data: userData });
  } catch (error) {
    console.error('获取用户资料失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 更新用户资料
router.put('/profile', async (req, res) => {
  try {
    console.log('更新用户资料请求:', req.body);
    
    // 从请求中获取用户ID和更新数据
    const userId = req.body.userId || req.headers['userid'];
    const { name, phone, email } = req.body;
    
    if (!userId) {
      return res.status(400).json({ success: false, message: '缺少用户ID' });
    }
    
    // 构建更新查询
    let updateFields = [];
    let updateValues = [];
    
    if (name) {
      updateFields.push('name = ?');
      updateValues.push(name);
    }
    
    if (phone) {
      updateFields.push('phone = ?');
      updateValues.push(phone);
    }
    
    if (email) {
      updateFields.push('email = ?');
      updateValues.push(email);
    }
    
    if (updateFields.length === 0) {
      return res.status(400).json({ success: false, message: '没有提供要更新的字段' });
    }
    
    // 添加userId到值数组
    updateValues.push(userId);
    
    // 更新用户信息 - 动态构建更新字段
    const query = `
      UPDATE users
      SET ${updateFields.join(', ')}
      WHERE userId = ?
    `;
    
    const [result] = await pool.query(query, updateValues);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '用户不存在或更新失败' });
    }
    
    // 返回成功信息
    res.json({ success: true, message: '用户资料更新成功' });
  } catch (error) {
    console.error('更新用户资料失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 上传头像
router.post('/avatar', upload.single('avatar'), async (req, res) => {
  try {
    console.log('上传头像请求:', req.file, req.body);
    
    if (!req.file) {
      return res.status(400).json({ success: false, message: '未上传文件' });
    }
    
    // 从请求中获取用户ID
    const userId = req.body.userId || req.headers['userid'];
    
    if (!userId) {
      return res.status(400).json({ success: false, message: '缺少用户ID' });
    }
    
    // 获取文件路径
    const avatarUrl = `/uploads/avatars/${req.file.filename}`;
    
    // 更新用户头像
    const query = `
      UPDATE users
      SET avatar = ?
      WHERE userId = ?
    `;
    
    const [result] = await pool.query(query, [avatarUrl, userId]);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '用户不存在或更新失败' });
    }
    
    // 返回成功信息和头像URL
    res.json({ success: true, message: '头像上传成功', data: { avatarUrl } });
  } catch (error) {
    console.error('上传头像失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

module.exports = router;